/**
 * Proj1.0.1
 * This JavaScript file is for Canvas view.
 */
// variables
// to show error messages or to accumulate them in error box
var showAlert = false;
// tab view tab control.
var myTabs;
// limit # friends per page
var limit = 10; // must match min option in pagesize combo
// current page #
var page = 1;
// array of friends to be invited
var arrFriends = [];
// name of viewer, in this app viewer == owner
var viewerName = '';
// minimum height
var minHeight = 250;
// array of person objects;
var g_arrPerson = [];

function proj1_init() {
    try {
		// Note: seek here for init() errors
		// show proper home view
		showHome(true);
		// fetch people and 
        fetchPeople(page);
        // lets prefetch tweets for a particular user
        // getTwitStream("cs6320vrr", "twitter");
        
        var listOptions = '<select id="pagesize" onchange="showMessage(pagesize.value);limit=pagesize.value;page=1;fetchPeople(page);"> ';
        listOptions += ' <option value="10">10</option>';
        listOptions += ' <option value="25">25</option>';
        listOptions += ' <option value="100">100</option></select>';
        document.getElementById("ddlist").innerHTML = listOptions;

        setupPageControls(PAGE_ID_HOME);
        
    } catch (err) {
        handleException("[proj1_init()] :" + err.description);
    }
}

function fetchPeople(nPage) {
    try {
        // clear array
        g_arrPerson = [];
        // Note: seek here for fetchPeople() errors
        // calculate start # based on page number passed.
        var myStart = parseInt((nPage - 1) * limit, 10);
        var req = opensocial.newDataRequest();
        req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
        // id specification
        var params = {};
        params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER;
        params[opensocial.IdSpec.Field.GROUP_ID] = 'FRIENDS';
        var idSpec = opensocial.newIdSpec(params);
        // options
        var opt_param = {};
        opt_param[opensocial.DataRequest.PeopleRequestFields.FIRST] = myStart;
        opt_param[opensocial.DataRequest.PeopleRequestFields.MAX] = limit;
        opt_param[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [ opensocial.Person.Field.STATUS, opensocial.Person.Field.PROFILE_URL, opensocial.Person.Field.ABOUT_ME];
        req.add(req.newFetchPeopleRequest(idSpec, opt_param), 'friends');
        // send request with an handler
        req.send(onLoadResponse);
    } catch (err) {
        handleException("[fetchPeople()] :" + err.description);
    }
}

/*
 * getFriendDetails() - queries container for person details.
 * id = id for the person
 */

function getFriendDetails(idx) {
    try {
        // navigate to page 2
        //navigateTab(PAGE_ID_FRIENDS);

        var person = g_arrPerson[idx];
        var name = person.getDisplayName();
        // show detail view
		showHome(false);

    	//1. get photo
        var profileThumbnail = person.getField(opensocial.Person.Field.THUMBNAIL_URL);
        //2. get URL
        var profilePage = person.getField(opensocial.Person.Field.PROFILE_URL);

        // set photo
        var text = "<a href=\"" + profilePage + "\" target=\"_parent\" >";
        text += "<img border=\"0\" src=\"" + profileThumbnail + "\" title=\"" + name + "\" alt=\"" + name + "\" height=\"100px\" width=\"100px\"/> </a>";
        //document.getElementById("friendsPhoto").innerHTML = text;
		document.getElementById("friendsPhoto").innerHTML = text;

        //3. get status
        var status = person.getField(opensocial.Person.Field.STATUS);
        //4. get about me
        var About = person.getField(opensocial.Person.Field.ABOUT_ME);
        text = "<ul> <li> Status: <em>" + status + "</em> </li>";
        text += "<li> About: " + About + "</li>";
        document.getElementById("friendsInfo").innerHTML = text;
		

        // get some more information.
/*
         * ADDRESSES
         * CURRENT_LOCATION
         * FOOD
         * FASHION
         * HUMOR
         * INTERESTS
         * /
        text = "<li> Location: <i>" + person.getField(opensocial.Person.Field.CURRENT_LOCATION) + "</i></li>";
        text += "<li> Pets: <i>" + person.getField(opensocial.Person.Field.PETS) + "</i></li>";
        text += "<li> Fashion: <i>" + person.getField(opensocial.Person.Field.FASHION) + "</i></li>";
        text += "<li> Humor: <i>" + person.getField(opensocial.Person.Field.HUMOR) + "</i></li>";
        text += "<li> Interests: <i>" + person.getField(opensocial.Person.Field.INTERESTS) + "</i></li>";
        text += "<li> EMAILS: <i>" + person.getField(opensocial.Person.Field.EMAILS) + "</i></li>";

        document.getElementById("friendsDetails").innerHTML = text;
		*/
		// this shall show twitter id for the friend
		//queryScrName("5", "friendsDetails");
		queryScrName(person.getId(), "friendsDetails");

    } catch (err) {
        // in case of err, navigate  to ERROR page
        // navigateTab(PAGE_ID_ERRORS);
        handleException("[getFriendDetails()]" + err.description);
    }
    gadgets.window.adjustHeight();
}


function onLoadResponse(data) {
    try {
        // seek here for .*[friendsHTML].* errors
        // get viewer object
        var viewer = data.get('viewer').getData();
        // show viewer name
        viewerName = viewer.getDisplayName();
        document.getElementById("viewer").innerHTML = 'Hello, ' + viewerName + ', your friends are,';
        // get friends data
        var friends = data.get('friends').getData();
        document.getElementById("viewerfriends").innerHTML = '';

        var localcount = 0;
        var inviteControls = '';

        var friends_html = '';

        friends_html += '<table border="0" cellpadding="1" cellspacing="1" width="100%">';
        friends.each(function (person) {
            // add this into temp array
            g_arrPerson.push(person);
            var name = person.getDisplayName();

            var friendDetails = "";
            friendDetails += "<tr width=\"100%\">";
            friendDetails += "<td align=\"left\" class=\"yui-content\"> ";
            friendDetails += "<a href=\"javascript:void();\" onclick=\"getFriendDetails(" + localcount + ");\">";
            friendDetails += name;
            friendDetails += "</a></td> </tr>";

            friends_html += friendDetails;
            // / maintain a local count to decide
            localcount++;
        });
        friends_html = friends_html + '</table>';
    } catch (err) {
        handleException("[onLoadResponse()] [friendsHTML]:" + err.description);
    }

    // setup pages
    setupPageControls(localcount);

    try {
        // / Note: seek here for .*[innerHTML].* exceptions
        document.getElementById("viewerfriends").innerHTML = friends_html;
    } catch (err) {
        handleException("[onLoadResponse()] [innerHTML]:" + err.description);
    }
    gadgets.window.adjustHeight();
}

/*
 * given count of #of people, it creates pagination controls.
 */

function setupPageControls(Count) {
    try {
        // Note: seek here for pageControls errors
        var pageControls = '';
        if (page != 1) {
            // show back button only when start != 0
            pageControls += '<input type=\"button\" class=\"yui-button yui-push-button\" onClick=\'page=page-1;fetchPeople(page);\' value=\'<\'  /> ';
        } else {
            pageControls += '<input type=\"button\" class=\"yui-button yui-push-button\" disabled value=\'<\'  /> ';
        }

        pageControls += 'Page [' + page + ']  ';

        if (Count == limit) {
            // if count matches, show next control
            // Problem: may show an extra button when pagination is exact
            pageControls += "<input type=\"button\" class=\"yui-button yui-push-button\" onClick=\"page=page+1;fetchPeople(page);\" value=\">\" /> ";
        } else {
            pageControls += "<input type=\"button\" class=\"yui-button yui-push-button\" disabled value=\">\" /> ";
        }
        document.getElementById("pageCtrl").innerHTML = pageControls;

    } catch (err) {
        handleException("[onLoadResponse()] [pageControls]:" + err.description);
    }
}

// this function will append current error text to error section
// err = string object


function handleException(err) {
    if (showAlert) {
        alert(err);
    }
    document.getElementById("errors").innerHTML += "<br/>" + err;
    gadgets.window.adjustHeight();
}

// this function will show alert message based on settings else bypass it.
// err = string object

function showMessage(err) {
    if (showAlert) {
        alert(err);
    }
}

function navigateTab(id) {
    try {
        myTabs.set('activeIndex', id);
    } catch (ex) {
        handleException("[navigateTab()]" + ex);
    }
}

////////////////////////////////////////////////////////////////////
//  showing and hiding spans 
////////////////////////////////////////////////////////////////////
function hideElement(idName) {
	try{
		
		//showMessage("hiding : " + document.getElementById(idName).innerHTML);
		document.getElementById(idName).style.visibility='hidden';
		document.getElementById(idName).style.display='none';
	}catch(ex){
		handleException("hideElement("+idName+") " + ex.description);
	}
}

function showElement(idName) {
	try{
		//showMessage("showing : " + document.getElementById(idName).innerHTML);
		document.getElementById(idName).style.visibility='visible';
		document.getElementById(idName).style.display='block';
	}catch(ex){
		handleException("showElement("+idName+") " + ex.description);
	}
}

// shows original home view
function showHome(all){
	if (all == true){
		// hide section 'viewFrn2'
		hideElement("viewerfriendDetails");
		// show section 'viewFrn1'
		showElement("viewerfriends");
		// show page controls
		showElement("pagingControls");
		// show viewer greetings
		showElement("viewer");
	} else {
		hideElement("viewerfriends");
		hideElement("pagingControls");
		hideElement("viewer");
		showElement("viewerfriendDetails");
	}
	gadgets.window.adjustHeight();
}
